package cn.wolfcode.web.controller;

import cn.wolfcode.domain.Employee;
import cn.wolfcode.qo.JSONResult;
import cn.wolfcode.service.IEmployeeService;
import cn.wolfcode.service.IPermissionService;
import cn.wolfcode.util.UserContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpSession;
import java.util.List;

@Controller
public class LoginController {
    @Autowired
    private IEmployeeService employeeService;
@Autowired
private IPermissionService permissionService;
    @RequestMapping("/login")
    @ResponseBody
    public JSONResult login(String username, String password,HttpSession session) {

        try {
            Employee employee= employeeService.login(username,password);
            //把当前登录的员工放到session中
            //session.setAttribute(UserContext.USER_IN_SESSION,employee);
            UserContext.setCurrentUser(employee);
            if(!employee.isAdmin()){
                //查询当前员工的所有权限表达式
                List<String> expressions = permissionService.selectByEmpId(employee.getId());
                //将权限表达式放到session中
                //session.setAttribute(UserContext.EXPRESSION_IN_SESSION,expressions);
                UserContext.setExpression(expressions);
            }

            return new JSONResult();
        } catch (Exception e) {
            e.printStackTrace();
            return new JSONResult(false,e.getMessage());
        }
    }
    @RequestMapping("/loginOut")
    public String LoginOut(HttpSession session){
        session.invalidate();
        return "redirect:/login.html";
    }
}
